<?php
namespace app\api\controller;

use support\Request;
use think\facade\Db;
use Webman\Push\Api;

class Chat
{
    /**
     * @param $uid
     * 根据uid来获取它的头像
     */
    public function get_head_one($uid)
    {
        $fromhead = Db::table('chat_user')->where('id', $uid)->select(['headimgurl'])->first();
        return $fromhead->headimgurl;
    }

    /**
     * @param $from_id
     * @param $to_id
     * 根据from_id来获取from_id同to_id发送的未读消息。
     */
    public function getCountNoread($from_id, $to_id)
    {
        return Db::table('chat_communication')->where(['from_id' => $from_id, 'to_id' => $to_id, 'is_read' => 0])->count('id');
    }

    /**
     * @param $from_id
     * @param $to_id
     * 根据from_id和to_id来获取他们聊天的最后一条数据
     */
    public function getLastMessage($from_id, $to_id)
    {
        $info = Db::table('chat_communication')->whereRaw('(from_id=' . $from_id . ' and to_id=' . $to_id . ') or (from_id=' . $to_id . ' and to_id=' . $from_id . ')')->orderBy('id', 'DESC')->limit(1)->first();
        return (json_decode(json_encode($info), true));
    }


    /**
     * 根据from_id来获取当前用户聊天列表
     */
    public function get_list(Request $request)
    {
        $param = $request->post();
        $info = Db::table('chat_communication')->where('to_uid', $param['uid'])->group('from_uid')->select()->each(function ($item){

            $item['time'] = date('Y-m-d H:i:s',$item['time']);
            $nickname = '-';
            $headimgurl = '-';
            $user = Db::table('chat_user')->where('id',$item['from_uid'])->find();
            if(!empty($user)){
                $nickname = $user['nickname'];
                $headimgurl = $user['headimgurl'];
            }
            $item['nickname']=$nickname;
            $item['headimgurl']=$headimgurl;
            return $item;
        });

        $res = [
            'code' => 200,
            'message' => 'success',
            'data' => $info
        ];

        return json($res);
    }


    /**
     * 根据from_id和to_uid来获取当前用户聊天记录
     */
    public function get_chat_history(Request $request)
    {
        $param = $request->post();
        if(empty($param['to_uid']) || empty($param['uid'])){
            return json([
                'code' => 300,
                'message' => '未获取到to_uid/uid',
                'data' => ''
            ]);
        }
        $list = Db::table('chat_communication')->where('from_uid|to_uid',$param['uid'])->whereOr('from_uid|to_uid',$param['to_uid'])->order('id asc')->paginate(500)->each(function ($item){

            return $item;
        });
        $res = [
            'code' => 200,
            'message' => 'success',
            'data' => $list
        ];

        return json($res);

    }

    function arraySort($array,$keys,$sort='desc') {
        $newArr = $valArr = array();
        foreach ($array as $key=>$value) {
            $valArr[$key] = $value[$keys];
        }
        ($sort == 'asc') ?  asort($valArr) : arsort($valArr);
        reset($valArr);
        foreach($valArr as $key=>$value) {
            $newArr[$key] = $array[$key];
        }
        return $newArr;
    }


    /**
     * 消息发送
     */
    public function send_chat(Request $request){
        $param = $request->post();
        if(empty($param['to_uid']) || empty($param['uid']) || empty($param['msg_content'])){
            return json([
                'code' => 300,
                'message' => '未获取到to_uid/uid',
                'data' => ''
            ]);
        }
        $api = new Api(
        // webman下可以直接使用config获取配置，非webman环境需要手动写入相应配置
            config('plugin.webman.push.app.api'),
            config('plugin.webman.push.app.app_key'),
            config('plugin.webman.push.app.app_secret')
        );
        // 给订阅 user-1 的所有客户端推送 message 事件的消息
        $api->trigger($param['to_uid'], 'message', [
            'from_uid' => $param['uid'],
            'content'  => $param['msg_content']
        ]);
        Db::table('chat_communication')->insert([
            'from_uid'=>$param['uid'],
            'to_uid'=>$param['to_uid'],
            'time'=>time(),
            'content'=>$param['msg_content'],
            'type'=>$param['type'],
        ]);
        return json([
            'code' => 200,
            'message' => '发送成功',
            'data' => ''
        ]);
    }
}
